package com.runtu.domain.trade.service.lock;

import com.runtu.domain.trade.adapter.repository.ITradeRepository;
import com.runtu.domain.trade.model.aggregate.GroupBuyOrderAggregate;
import com.runtu.domain.trade.model.entity.*;
import com.runtu.domain.trade.model.valobj.GroupBuyProgressVO;
import com.runtu.domain.trade.service.ITraderLockOrderService;
import com.runtu.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import com.runtu.types.design.framework.link.model2.chain.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName TraderOrderService
 * @Description TODO
 * @date 2025/8/6 9:58
 * @Version 1.0
 */
@Slf4j
@Service
public class TraderLockOrderService implements ITraderLockOrderService {


    @Resource
    private ITradeRepository tradeRepository;

    @Resource
    private BusinessLinkedList<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> tradeRuleFilter;


    @Override
    public MarketPayOrderEntity queryMarketPayOrderByOutTradeNo(String userId, String outTradeNo) {
        return tradeRepository.queryMarketPayOrderByOutTradeNo(userId,outTradeNo);
    }

    @Override
    public GroupBuyProgressVO querygroupbuyprogress(String teamId) {
        return tradeRepository.querygroupbuyprogress(teamId);
    }

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayActivityEntity payActivityEntity, PayDiscountEntity payDiscountEntity) throws Exception {
        log.info("拼团交易-锁定营销优惠支付订单:{} activityId:{} goodsId:{}", userEntity.getUserId(), payActivityEntity.getActivityId(), payDiscountEntity.getGoodsId());
        //先过滤一下 当前用户是否满足
        TradeLockRuleFilterBackEntity tradeLockRuleFilterBackEntity = tradeRuleFilter.apply(TradeLockRuleCommandEntity.builder()
                .activityId(payActivityEntity.getActivityId())
                .userId(userEntity.getUserId())
                .build(), new TradeLockRuleFilterFactory.DynamicContext());

        Integer userTakeOrderCount = tradeLockRuleFilterBackEntity.getUserTakeOrderCount();


        //通过聚合对象 封装后再传
        GroupBuyOrderAggregate groupBuyOrderAggregate = GroupBuyOrderAggregate.builder()
                .userEntity(userEntity)//用户的对象
                .payActivityEntity(payActivityEntity)//活动的对象
                .payDiscountEntity(payDiscountEntity)//优惠的对象
                .userTakeOrderCount(userTakeOrderCount)//
                .build();
        // 锁定聚合订单 - 这会用户只是下单还没有支付。后续会有2个流程；支付成功、超时未支付（回退）
        return tradeRepository.lockMarketPayOrder(groupBuyOrderAggregate);
    }
}
